package com.bianguo.android.bprinter.utils;

import android.os.Handler;
import android.os.Looper;

import com.bianguo.android.baselibrary.utils.MLog;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WPrintManager {

    private static volatile  WPrintManager instance;
    private Socket mSocket;
    private InputStream is;
    private OutputStream os;
    private ExecutorService executorService;
    private Handler mHandler;

    private WPrintManager() {
        mSocket = new Socket();
        executorService = Executors.newCachedThreadPool();
        mHandler = new Handler(Looper.myLooper());
    }

    public static WPrintManager getInstance() {
        WPrintManager manager = instance;
        if (manager == null) {
            synchronized (WPrintManager.class) {
                if (manager == null) {
                    manager = new WPrintManager();
                    instance = manager;
                }
            }
        }
        return manager;
    }

    /**
     * 连接打印机
     * @param ip 打印机ip地址
     * @param port 打印机端口号
     */
    public void connect(String ip, int port) {
        if (mSocket == null) {
            throw new NullPointerException("Socket不能为空");
        }
        executorService.execute(() -> {
            try {
                mSocket.connect(new InetSocketAddress(ip, port));
                mSocket.setKeepAlive(true);
                mSocket.setSoTimeout(5 * 1000);
                is = mSocket.getInputStream();
                os = mSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
                MLog.mLog("error : " + e.getMessage());
            }
        });
    }

    /**
     * 判断是否连接打印机
     * @return
     */
    public boolean isConnect() {
        if (mSocket == null) {
            return false;
        }
        return !mSocket.isClosed() && mSocket.isConnected();
    }

    /**
     * 断开连接
     */
    public void closeSocket() {
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (mSocket != null) {
                mSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
